package com.hsogoo.collate.datasource;

import com.google.common.collect.Maps;

import javax.sql.DataSource;
import java.util.*;

/**
 * @Author huangsaigang
 * Created @2019-10-25.
 */
public class DynamicDataSourceContextHolder {

    public static final String DEFAULT_DATASOURCE = "defaultDataSource";

    private static Map<String, DataSource> dataSourceMap = Maps.newHashMap();

    private static final ThreadLocal<String> contextHolder = new ThreadLocal<String>() {

        @Override
        protected String initialValue() {
            return DEFAULT_DATASOURCE;
        }
    };

    public static void addDataSource(String name, DataSource dataSource){
        dataSourceMap.put(name, dataSource);
    }

    public static DataSource getDataSource(String name){
        return dataSourceMap.get(name);
    }

    /**
     * 数据源的 key集合，用于切换时判断数据源是否存在
     */
    public static List<Object> dataSourceKeys = new ArrayList<>();

    /**
     * 切换数据源
     * @param key
     */
    public static void setDataSourceKey(String key) {
        contextHolder.set(key);
    }

    /**
     * 获取数据源
     * @return
     */
    public static String getDataSourceKey() {
        return contextHolder.get();
    }

    /**
     * 重置数据源
     */
    public static void clearDataSourceKey() {
        contextHolder.remove();
    }

    /**
     * 判断是否包含数据源
     * @param key 数据源key
     * @return
     */
    public static boolean containDataSourceKey(String key) {
        return dataSourceKeys.contains(key);
    }

    /**
     * 添加数据源keys
     * @param keys
     * @return
     */
    public static boolean addDataSourceKeys(Collection<? extends Object> keys) {
        return dataSourceKeys.addAll(keys);
    }
}
